package com.jiyinit.web.core.activiti.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.activiti.entity.TabProcessEntity;
import com.jiyinit.web.core.common.dto.PageRequest;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by user1 on 2018/7/16.
 */
@Controller
@RequestMapping(value = "/deploy")
public class DeployController {

    /**日志对象*/
    private final static Logger logger = LoggerFactory.getLogger(DeployController.class);

    @Resource(name = "repositoryService")
    private RepositoryService repositoryService;

    /**
     * 流程列表页面
     * @return
     */
    @RequestMapping(value = "/toProcessList", method = RequestMethod.GET)
    public String toProcessList(){
        return "activiti/processList";
    }

    /**
     * 流程部署页面
     * @return
     */
    @RequestMapping(value = "/toDeploy", method = RequestMethod.GET)
    public String toProcessDeploy(){
        return "activiti/deploy";
    }

    /**
     * 流程图页面
     * @return
     */
    @RequestMapping(value = "/toProcessImg", method = RequestMethod.GET)
    public String toProcessImg(){
        return "activiti/processImg";
    }

    /**
     * 获取流程信息列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getProcessList", method = RequestMethod.POST)
    public PagingResult<TabProcessEntity> getProcessList(PageRequest pageRequest) {
        int currentPage = pageRequest.getPage();
        int limit = 10;
        PagingResult<TabProcessEntity> pagingResult = new PagingResult<TabProcessEntity>();
        List<TabProcessEntity> rows = new ArrayList<>();

        if(currentPage > 0){
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage((currentPage - 1) * limit, limit);
            int total = repositoryService.createProcessDefinitionQuery().list().size();

            for (ProcessDefinition i : list) {
                TabProcessEntity p = new TabProcessEntity();
                p.setDeploymentId(i.getDeploymentId());
                p.setId(i.getId());
                p.setKey(i.getKey());
                p.setName(i.getName());
                p.setResourceName(i.getResourceName());
                p.setDiagramResourceName(i.getDiagramResourceName());
                p.setVersion(i.getVersion());
                rows.add(p);
            }

            pagingResult.setCurrentPage(currentPage);
            pagingResult.setTotalRecords(total);
            pagingResult.setRows(rows);
        }

        return pagingResult;
    }

    /**
     * 流程部署
     * @param processFile
     * @return
     */
    @RequestMapping(value = "/deployProcess", method = RequestMethod.POST)
    public String deployProcess(@RequestParam MultipartFile processFile, HttpServletRequest request) {
        try {
            MultipartFile file = processFile;
            String filename = file.getOriginalFilename();
            logger.info("filename: {}" + filename);
            InputStream is = file.getInputStream();
            repositoryService.createDeployment().addInputStream(filename, is).deploy();
            request.setAttribute("deployStatus", "0");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("deployStatus", "-1");
        }
        return "activiti/deploy";
    }

    /**
     * 查看已部署流程的流程图
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/showProcessImg", method = RequestMethod.GET)
    public void showProcessImg(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String pId = request.getParameter("pid");
        String resource = request.getParameter("resource");
        ProcessDefinition def = repositoryService.createProcessDefinitionQuery().processDefinitionId(pId).singleResult();
        InputStream is = repositoryService.getResourceAsStream(def.getDeploymentId(), resource);
        ServletOutputStream out = response.getOutputStream();
        /*IOUtils.copy(is, output);*/
        response.setContentType("image/png");
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = is.read(b, 0, 1024)) != -1) {
            out.write(b, 0, len);
        }
        out.close();
        is.close();
    }

    /**
     * 删除流程 (批量)
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteProcess", method = RequestMethod.POST)
    public ResponseEntity<ResponseDto> deleteProcess(HttpServletRequest request){
        String idStrs = request.getParameter("ids");
        String[] ids = idStrs.split(",");
        if(!Check.isNullObject(ids)){
            for (int i = 0; i < ids.length; i++){
                //级联删除，如果 boolean值为true时，会删除所有和当前部署的规则相关的信息，包括历史的信息。
                repositoryService.deleteDeployment(ids[i], true);
            }
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
}
